/* eslint-disable */
<template>
  <div class="label">
    <n-space vertical>
      <n-space style="margin: 20px 10px">
        <n-button type="primary" @click="addGroup"> 添加分组 </n-button>
        <n-button type="success" @click="addLabel"> 添加标签 </n-button>
        <!-- <n-button type="error"> 批量删除 </n-button> -->
      </n-space>
      <n-tabs
        type="bar"
        placement="left"
        v-model:value="activeTab"
        @update:value="handleTabChange"
      >
        <n-tab-pane name="all" tab="全部">
          <div style="width: 300px; margin: 10px 0">
            <n-input-group>
              <n-input
                multiple
                v-model:value="labelQuery.keyword"
                clearable
                placeholder="请输入标签关键词"
              />
              <n-button @click="getLabelList" type="primary" ghost>
                搜索
              </n-button>
            </n-input-group>
          </div>
          <div class="box" :style="`height:${innerHeights}`">
            <div class="table-box">
              <n-data-table
                ref="table"
                striped
                :columns="columns"
                :data="labelData"
              />
            </div>

            <div class="pagination">
              <n-pagination
                :page="labelQuery.pageNum"
                :page-size="labelQuery.pageSize"
                :item-count="total"
                size="medium"
                show-size-picker
                :page-slot="8"
                :page-sizes="pageSizes"
                :on-update:page="pageNext"
                :on-update:page-size="sizeNext"
              >
                <template #prefix="{ itemCount }">
                  共{{ itemCount }}条数据
                </template>
              </n-pagination>
            </div>
          </div>
        </n-tab-pane>
        <n-tab-pane
          v-for="item in groupData"
          :name="item.id"
          :tab="item.label"
          :key="item.id"
        >
          <div style="margin: 10px; width: 500px">
            <n-input-group>
              <n-button
                tertiary
                type="info"
                @click="editGroup(item)"
                style="margin-right: 10px"
              >
                编辑分组
              </n-button>
              <n-popconfirm @positive-click="delGroup(item.id)">
                <template #trigger>
                  <n-button style="margin-right: 10px" tertiary type="error"
                    >删除分组
                  </n-button>
                </template>
                请确认是否删除分组
              </n-popconfirm>
              <n-input
                multiple
                v-model:value="labelQuery.keyword"
                clearable
                placeholder="请输入标签关键词"
              />
              <n-button @click="getLabelList" type="primary" ghost>
                搜索
              </n-button>
            </n-input-group>
          </div>
          <div class="box" :style="`height:${innerHeights}`">
            <div class="table-box">
              <n-data-table
                ref="table"
                striped
                :columns="columns"
                :data="labelData"
              />
            </div>
            <div class="pagination">
              <n-pagination
                :page="labelQuery.pageNum"
                :page-size="labelQuery.pageSize"
                :item-count="total"
                size="medium"
                show-size-picker
                :page-slot="8"
                :page-sizes="pageSizes"
                :on-update:page="pageNext"
                :on-update:page-size="sizeNext"
              >
                <template #prefix="{ itemCount }">
                  共{{ itemCount }}条数据
                </template>
              </n-pagination>
            </div>
          </div>
        </n-tab-pane>
      </n-tabs>
    </n-space>

    <!-- 分组 -->
    <yingModal
      :width="'500px'"
      :height="'400px'"
      :title="title"
      @close="share(0)"
      :SkuShow="groupShow"
      @confirm="submitGruopForm"
    >
      <template #content>
        <div>
          <n-form
            ref="groupFormRef"
            :model="groupForm"
            :rules="rules"
            class="item_top"
          >
            <n-form-item label="组织名称" path="groupName">
              <n-input
                style="width: 100%"
                v-model:value="groupForm.groupName"
              />
            </n-form-item>
            <n-form-item label="排序" path="sort">
              <n-input-number
                style="width: 100%"
                :min="0"
                v-model:value="groupForm.sort"
                clearable
              />
            </n-form-item>
          </n-form>
        </div>
      </template>
    </yingModal>

    <!-- 标签 -->
    <yingModal
      :width="'800px'"
      :height="'460px'"
      :title="title"
      @close="share(0)"
      :SkuShow="labelShow"
      @confirm="submitLabelForm"
    >
      <template #content>
        <div>
          <n-form
            ref="labelFormRef"
            :model="labelForm"
            :rules="rules"
            class="item_top"
          >
            <n-grid :cols="2" :x-gap="24">
              <n-form-item-gi label="标签名称" path="labelName">
                <n-input v-model:value="labelForm.labelName" clearable />
              </n-form-item-gi>
              <n-form-item-gi label="标签类型" path="labelType">
                <n-select
                  v-model:value="labelForm.labelType"
                  :options="labelTypeOptions"
                  clearable
                >
                </n-select>
              </n-form-item-gi>
            </n-grid>

            <n-grid :cols="2" :x-gap="24">
              <n-form-item-gi label="分组" path="labelGrounpId">
                <n-select
                  v-model:value="labelForm.labelGrounpId"
                  :options="groupData"
                  :multiple="!isEdit"
                  clearable
                >
                </n-select>
              </n-form-item-gi>
              <n-form-item-gi label="使用类型" path="useType">
                <n-select
                  v-model:value="labelForm.useType"
                  :options="useTypeOptions"
                  clearable
                >
                </n-select>
              </n-form-item-gi>
            </n-grid>

            <n-grid :cols="3" :x-gap="24">
              <n-form-item-gi label="排序" path="sort">
                <n-input-number
                  style="width: 100%"
                  :min="0"
                  v-model:value="labelForm.sort"
                  clearable
                />
              </n-form-item-gi>
              <n-form-item-gi label="自定义" path="setting">
                <n-radio-group v-model:value="labelForm.setting">
                  <n-space>
                    <n-radio key="常规" value="1"> 常规 </n-radio>
                    <n-radio key="图片" value="2"> 图片 </n-radio>
                  </n-space>
                </n-radio-group>
              </n-form-item-gi>
              <n-form-item-gi path="image" v-if="labelForm.setting == '2'">
                <div
                  @click="imgShow = true"
                  v-if="labelForm.image"
                  style="
                    height: 135px;
                    width: 100px;
                    overflow: hidden;
                    display: flex;
                    padding: 0px;
                    justify-content: center;
                    align-items: center;
                  "
                >
                  <n-image
                    :preview-disabled="true"
                    style="
                      object-fit: contain;
                      display: flex;
                      justify-content: center;
                      align-items: center;
                      border: 1px solid #eee;
                    "
                    :src="Https() + labelForm.image"
                  />
                </div>
                <div v-else @click="imgShow = true" class="imageUpload">
                  <n-icon size="24" color="rgb(49, 108, 114)">
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      xmlns:xlink="http://www.w3.org/1999/xlink"
                      viewBox="0 0 16 16"
                    >
                      <g fill="none">
                        <path
                          d="M8 2.5a.5.5 0 0 0-1 0V7H2.5a.5.5 0 0 0 0 1H7v4.5a.5.5 0 0 0 1 0V8h4.5a.5.5 0 0 0 0-1H8V2.5z"
                          fill="currentColor"
                        ></path>
                      </g>
                    </svg>
                  </n-icon>
                </div>
              </n-form-item-gi>
            </n-grid>

            <n-grid :cols="3" :x-gap="24">
              <n-form-item-gi label="字体颜色" path="fontColor">
                <n-color-picker
                  v-model:value="labelForm.fontColor"
                  :actions="['clear']"
                />
              </n-form-item-gi>
              <n-form-item-gi label="背景颜色" path="backgroundColor">
                <n-color-picker
                  v-model:value="labelForm.backgroundColor"
                  :actions="['clear']"
                />
              </n-form-item-gi>
              <n-form-item-gi label="边框颜色" path="borderColor">
                <n-color-picker
                  v-model:value="labelForm.borderColor"
                  :actions="['clear']"
                />
              </n-form-item-gi>
            </n-grid>

            <n-grid :cols="2" :x-gap="24">
              <n-form-item-gi label="状态" path="status">
                <n-radio-group v-model:value="labelForm.status">
                  <n-space>
                    <n-radio key="启用" value="1"> 启用 </n-radio>
                    <n-radio key="不启用" value="0"> 不启用 </n-radio>
                  </n-space>
                </n-radio-group>
              </n-form-item-gi>
            </n-grid>
          </n-form>
        </div>
      </template>
    </yingModal>
    <n-modal
      v-model:show="imgShow"
      :mask-closable="false"
      preset="dialog"
      style="width: 1000px"
      :title="'文件管理'"
      content="你确认?"
      positive-text="确定"
      negative-text="关闭"
      @positive-click="imgShow = false"
      @negative-click="imgShow = false"
    >
      <div class="box-upload">
        <Upload type="1" @selectImage="selectImageFun" />
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import api from "./api";
import { Https } from "@/utils";
import Upload from "@/views/upload/index.vue";
import yingModal from "@/components/common/YingModal.vue";
import { h, onMounted, ref } from "vue";
import { FormInst, NButton, useMessage, NSwitch } from "naive-ui";
const message = useMessage();
const groupFormRef = ref<FormInst | null>(null);
const labelFormRef = ref<FormInst | null>(null);
const innerHeights = ref(0);
const total = ref(0);
const activeTab = ref("all");
const groupShow = ref(false);
const labelShow = ref(false);
const isEdit = ref(false);
const imgShow = ref(false);
const title = ref("");
const groupData = ref([]);
const labelData = ref([]);
const groupQuery = ref({
  pageNum: 1,
  pageSize: 20,
  keyword: "",
});
const labelQuery = ref({
  pageNum: 1,
  pageSize: 20,
  group_id: 0,
  keyword: "",
});
const pageSizes = [
  {
    label: "5 每页",
    value: 5,
  },
  {
    label: "10 每页",
    value: 10,
  },
  {
    label: "20 每页",
    value: 20,
  },
  {
    label: "30 每页",
    value: 30,
  },
  {
    label: "40 每页",
    value: 40,
  },
];
const labelTypeOptions = [
  { label: "商品标签", value: "商品标签" },
  { label: "非商品标签", value: "非商品标签" },
];

const useTypeOptions = [
  { label: "微信小程序", value: "微信小程序" },
  { label: "PC后台", value: "PC后台" },
  { label: "游戏开发", value: "游戏开发" },
];

const groupForm = ref({
  id: null,
  groupName: "",
  sort: null,
});

const labelForm = ref({
  id: null,
  labelName: "",
  labelType: "",
  labelGrounpId: [],
  useType: "",
  setting: "1",
  fontColor: "",
  backgroundColor: "",
  borderColor: "",
  sort: null,
  status: "1",
  image: "",
});

const rules = {
  groupName: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入",
  },
  sort: {
    type: "number",
    required: true,
    trigger: ["blur", "input"],
    message: "请输入",
  },
  labelName: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入",
  },
  labelType: {
    required: true,
    trigger: "blur",
    message: "请选择",
  },
  labelGrounpId: {
    required: true,
    trigger: "blur",
    message: "请选择",
    validator(rule: any, value: any) {
      if (!value || value.length == 0) {
        return new Error("请选择");
      }
      return true;
    },
  },
  useType: {
    required: true,
    trigger: "blur",
    message: "请选择",
  },
  fontColor: {
    required: true,
    trigger: "blur",
    message: "请选择",
  },
  backgroundColor: {
    required: true,
    trigger: "blur",
    message: "请选择",
  },
  borderColor: {
    required: true,
    trigger: "blur",
    message: "请选择",
  },
};
const columns = [
  {
    title: "标签",
    key: "labelName",
    ellipsis: {
      tooltip: true,
    },
    render(row: any) {
      return h(
        "span",
        {
          style: {
            color: row.fontColor,
            backgroundColor: row.backgroundColor,
            border: `1px solid ${row.borderColor}`,
            padding: "4px 8px",
            borderRadius: "4px",
            display: "inline-block",
          },
        },
        row.labelName,
      );
    },
  },
  {
    title: "字体颜色",
    key: "fontColor",
    ellipsis: {
      tooltip: true,
    },
    render(row: any) {
      return h("div", {
        style: {
          width: "30px",
          height: "24px",
          backgroundColor: row.fontColor,
          borderRadius: "4px",
        },
      });
    },
  },
  {
    title: "背景颜色",
    key: "backgroundColor",
    ellipsis: {
      tooltip: true,
    },
    render(row: any) {
      return h("div", {
        style: {
          width: "30px",
          height: "24px",
          backgroundColor: row.backgroundColor,
          borderRadius: "4px",
        },
      });
    },
  },
  {
    title: "边框颜色",
    key: "borderColor",
    ellipsis: {
      tooltip: true,
    },
    render(row: any) {
      return h("div", {
        style: {
          width: "30px",
          height: "24px",
          backgroundColor: row.borderColor,
          borderRadius: "4px",
        },
      });
    },
  },
  {
    title: "标签类型",
    key: "labelType",
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: "使用类型",
    key: "useType",
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: "状态",
    key: "status",
    ellipsis: {
      tooltip: true,
    },
    render(row: any) {
      return h(NSwitch, {
        value: row.status,
        disabled: true,
      });
    },
  },
  {
    title: "操作",
    key: "actions",
    width: 180,
    align: "right",
    fixed: "right",
    hideInExcel: true,
    ellipsis: {
      tooltip: true,
    },
    render(row: any) {
      return [
        h(
          NButton,
          {
            size: "small",
            type: "primary",
            secondary: true,
            onClick: () => editLabel(row),
          },
          {
            default: () => "编辑",
            icon: () => h("i", { class: "i-fe:database" }),
          },
        ),

        h(
          NButton,
          {
            size: "small",
            type: "error",
            style: "margin-left: 12px;",
            onClick: () => delLabel(row.id),
          },
          {
            default: () => "删除",
            icon: () =>
              h("i", { class: "i-material-symbols:delete-outline text-14" }),
          },
        ),
      ];
    },
  },
];
function pageNext(page: any) {
  labelQuery.value.pageNum = page;
  getLabelList();
}
function sizeNext(size: any) {
  labelQuery.value.pageNum = 1;
  labelQuery.value.pageSize = size;
  getLabelList();
}

async function getGroupList() {
  const res = await api.goodsGroupListApi(groupQuery.value);
  if ((res as any).code == 200) {
    groupData.value = res.data.list.map((item: any) => ({
      label: item.groupName,
      value: item.id,
      id: item.id,
      sort: item.sort,
    }));
  }
}
async function getLabelList() {
  const res = await api.goodsLabelListApi(labelQuery.value);
  if ((res as any).code == 200) {
    labelData.value = res.data.list;
    total.value = res.data.total;
  }
}

function handleTabChange(id: any) {
  labelQuery.value.pageNum = 1;
  labelQuery.value.pageSize = 20;
  labelQuery.value.keyword = "";
  labelQuery.value.group_id = typeof id == "number" ? id : 0;
  getLabelList();
}

function addGroup() {
  groupShow.value = true;
  title.value = "添加分组";
}

function addLabel() {
  labelShow.value = true;
  title.value = "添加标签";
}

function submitGruopForm() {
  groupFormRef.value?.validate(async (errors) => {
    if (!errors) {
      if (groupForm.value.id == null) {
        const res = await api.goodsGroupAddApi(groupForm.value);
        share(res);
      } else {
        const res = await api.goodsGroupEditApi(groupForm.value);
        share(res);
      }
    } else {
      message.error("有未填项！");
    }
  });
}

function editGroup(item: any) {
  groupForm.value = item;
  groupForm.value.groupName = item.label;
  groupShow.value = true;
  title.value = "编辑分组";
}

async function delGroup(group_id: any) {
  const data = { id: group_id };
  const res = await api.goodsGroupDelApi(data);
  share(res);
}

function submitLabelForm() {
  labelFormRef.value?.validate(async (errors) => {
    if (!errors) {
      if (labelForm.value.id == null) {
        const res = await api.goodsLabelAddApi(labelForm.value);
        share(res);
      } else {
        const res = await api.goodsLabelEditApi(labelForm.value);
        share(res);
      }
    } else {
      console.log(errors);
    }
  });
}

function editLabel(row: any) {
  title.value = "编辑标签";
  isEdit.value = true;
  labelShow.value = true;
  labelForm.value = JSON.parse(JSON.stringify(row));
  labelForm.value.status = row.status ? "1" : "0";
  labelForm.value.labelGrounpId = Array.isArray(row.labelGrounpId)
    ? row.labelGrounpId[0]
    : row.labelGrounpId;
}

async function delLabel(label_id: any) {
  const data = { id: label_id };
  const res = await api.goodsLabelDelApi(data);
  share(res);
}

function share(res: any) {
  if (res.code == 200) {
    message.success("成功");
    getGroupList();
    getLabelList();
  }
  groupShow.value = false;
  labelShow.value = false;
  isEdit.value = false;
  groupForm.value = {
    id: null,
    groupName: "",
    sort: null,
  };
  labelForm.value = {
    id: null,
    labelName: "",
    labelType: "",
    labelGrounpId: [],
    useType: "",
    setting: "1",
    fontColor: "",
    backgroundColor: "",
    borderColor: "",
    sort: null,
    status: "1",
    image: "",
  };
}
const selectImageFun = (selectImageList: any) => {
  labelForm.value.image = selectImageList[0];
  imgShow.value = false;
};

onMounted(() => {
  getGroupList();
  getLabelList();
});
</script>

<style>
.pagination {
  display: flex;
  justify-content: right;
  /* height: 60px; */
  gap: 10px;
  align-items: center;
  position: relative;
  top: 20px;
  right: 30px;
}
</style>
